package com.christina.engine.processing.impl;

import com.christina.engine.execution.model.ExecutionResult;
import com.christina.engine.intent.model.Intent;
import com.christina.engine.processing.AbstractRequestProcessor;
import com.christina.engine.processing.model.ProcessingContext;
import com.christina.engine.processing.model.ProcessingResult;
import com.christina.engine.routing.model.RoutingDecision;
import com.christina.service.application.model.UnifiedResponse;
import com.christina.service.application.model.UnifiedResponse.UnifiedResponseBuilder;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * 响应处理器
 * 负责构建最终的统一响应，整合所有处理结果
 */
@Component
public class ResponseProcessor extends AbstractRequestProcessor {
    
    private static final String PROCESSOR_NAME = "ResponseProcessor";
    private static final int PROCESSOR_ORDER = 700; // 在执行处理器之后执行，作为链的最后一环
    
    public ResponseProcessor() {
        super(PROCESSOR_NAME, PROCESSOR_ORDER);
    }
    
    @Override
    protected ProcessingResult doProcess(ProcessingContext context) {
        logger.debug("Starting response building for requestId: {}", context.getRequestId());
        
        try {
            // 获取执行结果
            ExecutionResult executionResult = getExecutionResult(context);
            
            // 构建响应内容
            String responseContent = buildResponseContent(context, executionResult);
            
            // 构建响应元数据
            Map<String, Object> responseMetadata = buildResponseMetadata(context, executionResult);
            
            // 更新响应构建器
            updateResponseBuilder(context, executionResult, responseContent, responseMetadata);
            
            // 评估响应质量
            double responseQuality = evaluateResponseQuality(context, responseContent, responseMetadata);
            
            // 存储响应处理信息
            context.setProcessingData("responseContent", responseContent);
            context.setProcessingData("responseMetadata", responseMetadata);
            context.setProcessingData("responseQuality", responseQuality);
            
            // 如果响应质量较低，记录警告
            if (responseQuality < 0.6) {
                logger.warn("Low quality response for requestId: {}, quality: {}", 
                        context.getRequestId(), responseQuality);
            }
            
            logger.debug("Response building completed for requestId: {}, quality: {}", 
                    context.getRequestId(), responseQuality);
            
            return ProcessingResult.builder()
                    .success(true)
                    .shouldContinue(false) // 响应处理器是链的最后一环，不需要继续
                    .processorName(PROCESSOR_NAME)
                    .resultData("responseContent", responseContent)
                    .resultData("responseQuality", responseQuality)
                    .resultData("responseLength", responseContent.length())
                    .resultData("metadataCount", responseMetadata.size())
                    .build();
                    
        } catch (Exception e) {
            logger.error("Error during response building for requestId: {}", context.getRequestId(), e);
            throw e;
        }
    }
    
    /**
     * 获取执行结果
     */
    private ExecutionResult getExecutionResult(ProcessingContext context) {
        ExecutionResult executionResult = (ExecutionResult) context.getProcessingData().get("executionResult");
        
        if (executionResult == null) {
            logger.warn("No execution result found, creating default error result");
            return ExecutionResult.builder()
                    .success(false)
                    .errorMessage("处理过程中出现异常，请稍后重试")
                    .executorName("Unknown")
                    .executionDurationMs(0L)
                    .build();
        }
        
        return executionResult;
    }
    
    /**
     * 构建响应内容
     */
    private String buildResponseContent(ProcessingContext context, ExecutionResult executionResult) {
        if (executionResult.isSuccess()) {
            return buildSuccessResponse(context, executionResult);
        } else {
            return buildErrorResponse(context, executionResult);
        }
    }
    
    /**
     * 构建成功响应
     */
    private String buildSuccessResponse(ProcessingContext context, ExecutionResult executionResult) {
        StringBuilder response = new StringBuilder();
        
        // 获取业务结果数据
        Object resultData = executionResult.getResultData();
        
        if (resultData != null) {
            // 如果有具体的业务结果，直接使用
            response.append(resultData.toString());
        } else {
            // 如果没有具体结果，根据意图类型生成通用响应
            response.append(generateGenericSuccessResponse(context));
        }
        
        // 添加个性化元素
        addPersonalizationElements(response, context);
        
        return response.toString();
    }
    
    /**
     * 构建错误响应
     */
    private String buildErrorResponse(ProcessingContext context, ExecutionResult executionResult) {
        StringBuilder response = new StringBuilder();
        
        // 获取错误信息
        String errorMessage = executionResult.getErrorMessage();
        
        if (errorMessage != null && !errorMessage.trim().isEmpty()) {
            // 使用具体的错误信息
            response.append("抱歉，").append(errorMessage);
        } else {
            // 使用通用错误信息
            response.append("抱歉，处理您的请求时遇到了问题，请稍后重试。");
        }
        
        // 添加建议性内容
        addSuggestiveContent(response, context);
        
        return response.toString();
    }
    
    /**
     * 生成通用成功响应
     */
    private String generateGenericSuccessResponse(ProcessingContext context) {
        Intent recognizedIntent = context.getRecognizedIntent();
        
        if (recognizedIntent == null) {
            return "您的请求已处理完成。";
        }
        
        return switch (recognizedIntent.getType()) {
            case TRAVEL_PLANNING -> "我已为您制定了出行方案，请查看详细信息。";
            case GENERAL_CHAT -> "很高兴与您聊天！";
            case USER_PROFILE -> "您的个人信息已更新。";
            case TASK_CREATION -> "任务已创建成功。";
            case HELP_REQUEST -> "希望这些信息对您有帮助。";
            default -> "您的请求已处理完成。";
        };
    }
    
    /**
     * 添加个性化元素
     */
    private void addPersonalizationElements(StringBuilder response, ProcessingContext context) {
        // 根据用户偏好添加个性化内容
        if (context.getUserContext() != null && 
            context.getUserContext().getProfile() != null) {
            
            String language = context.getUserContext().getProfile().getLanguage();
            if ("en".equals(language)) {
                // 如果用户偏好英语，可以添加英语提示
                response.append("\n\n(English support available)");
            }
        }
        
        // 根据时间添加问候语
        LocalDateTime now = LocalDateTime.now();
        int hour = now.getHour();
        
        if (hour >= 6 && hour < 12) {
            response.append("\n\n祝您早上愉快！");
        } else if (hour >= 12 && hour < 18) {
            response.append("\n\n祝您下午愉快！");
        } else if (hour >= 18 && hour < 22) {
            response.append("\n\n祝您晚上愉快！");
        }
    }
    
    /**
     * 添加建议性内容
     */
    private void addSuggestiveContent(StringBuilder response, ProcessingContext context) {
        Intent recognizedIntent = context.getRecognizedIntent();
        
        if (recognizedIntent != null) {
            switch (recognizedIntent.getType()) {
                case TRAVEL_PLANNING:
                    response.append("\n\n您可以尝试提供更详细的出行信息，如具体的出发时间、目的地等。");
                    break;
                case GENERAL_CHAT:
                    response.append("\n\n您可以问我其他问题，我很乐意为您提供帮助。");
                    break;
                case HELP_REQUEST:
                    response.append("\n\n如需更多帮助，请联系我们的客服团队。");
                    break;
                default:
                    response.append("\n\n如果问题持续存在，请稍后重试或联系客服。");
            }
        }
    }
    
    /**
     * 构建响应元数据
     */
    private Map<String, Object> buildResponseMetadata(ProcessingContext context, ExecutionResult executionResult) {
        Map<String, Object> metadata = new HashMap<>();
        
        // 基本信息
        metadata.put("requestId", context.getRequestId());
        metadata.put("responseTime", LocalDateTime.now());
        metadata.put("processingSuccess", executionResult.isSuccess());
        
        // 意图信息
        if (context.getRecognizedIntent() != null) {
            metadata.put("intentType", context.getRecognizedIntent().getType().name());
            metadata.put("intentConfidence", context.getRecognizedIntent().getConfidence());
        }
        
        // 路由信息
        RoutingDecision routingDecision = (RoutingDecision) context.getProcessingData().get("routingDecision");
        if (routingDecision != null) {
            metadata.put("targetService", routingDecision.getTargetService());
            metadata.put("routingConfidence", routingDecision.getConfidence());
        }
        
        // 执行信息
        metadata.put("executorName", executionResult.getExecutorName());
        metadata.put("executionDuration", executionResult.getExecutionDurationMs());
        
        // 处理质量信息
        addQualityMetadata(metadata, context);
        
        // 性能信息
        addPerformanceMetadata(metadata, context);
        
        return metadata;
    }
    
    /**
     * 添加质量元数据
     */
    private void addQualityMetadata(Map<String, Object> metadata, ProcessingContext context) {
        // 意图识别质量
        Double intentQuality = calculateIntentQuality(context);
        if (intentQuality != null) {
            metadata.put("intentQuality", intentQuality);
        }
        
        // 路由质量
        Double routingQuality = (Double) context.getProcessingData().get("routingQuality");
        if (routingQuality != null) {
            metadata.put("routingQuality", routingQuality);
        }
        
        // 执行质量
        Double executionQuality = (Double) context.getProcessingData().get("executionQuality");
        if (executionQuality != null) {
            metadata.put("executionQuality", executionQuality);
        }
    }
    
    /**
     * 添加性能元数据
     */
    private void addPerformanceMetadata(Map<String, Object> metadata, ProcessingContext context) {
        // 处理事件数量
        if (context.getEvents() != null) {
            metadata.put("eventCount", context.getEvents().size());
        }
        
        // 处理数据大小
        metadata.put("processingDataSize", context.getProcessingData().size());
        
        // 上下文信息
        metadata.put("hasUserContext", context.getUserContext() != null);
        metadata.put("hasConversationContext", context.getConversationContext() != null);
    }
    
    /**
     * 计算意图识别质量
     */
    private Double calculateIntentQuality(ProcessingContext context) {
        Intent intent = context.getRecognizedIntent();
        if (intent == null) {
            return null;
        }
        
        double baseScore = intent.getConfidence();
        
        // 根据意图参数的完整性调整分数
        double parameterScore = 0.5;
        if (intent.getParameters() != null && !intent.getParameters().isEmpty()) {
            parameterScore = 0.8;
        }
        
        return (baseScore * 0.7 + parameterScore * 0.3);
    }
    
    /**
     * 更新响应构建器
     */
    private void updateResponseBuilder(ProcessingContext context, ExecutionResult executionResult, 
                                     String responseContent, Map<String, Object> responseMetadata) {
        
        UnifiedResponseBuilder responseBuilder = context.getResponseBuilder();
        
        // 设置基本响应信息
        responseBuilder
                .success(executionResult.isSuccess())
                .content(responseContent)
                .responseTime(LocalDateTime.now());
        
        // 设置意图信息
        if (context.getRecognizedIntent() != null) {
            responseBuilder.intent(context.getRecognizedIntent());
        }
        
        // 设置决策结果
        if (context.getDecisionResult() != null) {
            responseBuilder.decisionResult(context.getDecisionResult());
        }
        
        // 设置业务结果
        if (executionResult.getResultData() != null) {
            responseBuilder.businessResult(executionResult.getResultData());
        }
        
        // 设置错误信息
        if (!executionResult.isSuccess()) {
            responseBuilder.errorMessage(executionResult.getErrorMessage());
        }
        
        // 设置元数据
        responseBuilder.metadata(responseMetadata);
    }
    
    /**
     * 评估响应质量
     */
    private double evaluateResponseQuality(ProcessingContext context, String responseContent, 
                                         Map<String, Object> responseMetadata) {
        
        double contentScore = evaluateContentQuality(responseContent);
        double metadataScore = evaluateMetadataQuality(responseMetadata);
        double contextScore = evaluateContextUtilization(context);
        
        return (contentScore * 0.5 + metadataScore * 0.3 + contextScore * 0.2);
    }
    
    /**
     * 评估内容质量
     */
    private double evaluateContentQuality(String content) {
        if (content == null || content.trim().isEmpty()) {
            return 0.0;
        }
        
        double score = 0.5; // 基础分数
        
        // 根据内容长度调整分数
        int length = content.length();
        if (length >= 10 && length <= 500) {
            score += 0.3; // 合适的长度
        } else if (length > 500) {
            score += 0.1; // 内容较长
        }
        
        // 根据内容结构调整分数
        if (content.contains("\n")) {
            score += 0.1; // 有结构化内容
        }
        
        // 根据礼貌用语调整分数
        if (content.contains("请") || content.contains("谢谢") || content.contains("祝您")) {
            score += 0.1; // 有礼貌用语
        }
        
        return Math.min(1.0, score);
    }
    
    /**
     * 评估元数据质量
     */
    private double evaluateMetadataQuality(Map<String, Object> metadata) {
        if (metadata == null || metadata.isEmpty()) {
            return 0.0;
        }
        
        double score = 0.3; // 基础分数
        
        // 必要字段检查
        String[] requiredFields = {"requestId", "responseTime", "processingSuccess"};
        for (String field : requiredFields) {
            if (metadata.containsKey(field)) {
                score += 0.1;
            }
        }
        
        // 质量字段检查
        String[] qualityFields = {"intentQuality", "routingQuality", "executionQuality"};
        for (String field : qualityFields) {
            if (metadata.containsKey(field)) {
                score += 0.1;
            }
        }
        
        return Math.min(1.0, score);
    }
    
    /**
     * 评估上下文利用度
     */
    private double evaluateContextUtilization(ProcessingContext context) {
        double score = 0.0;
        
        if (context.getRecognizedIntent() != null) {
            score += 0.3;
        }
        
        if (context.getUserContext() != null) {
            score += 0.3;
        }
        
        if (context.getConversationContext() != null) {
            score += 0.2;
        }
        
        if (context.getProcessingData().containsKey("routingDecision")) {
            score += 0.1;
        }
        
        if (context.getProcessingData().containsKey("executionResult")) {
            score += 0.1;
        }
        
        return score;
    }
    
    @Override
    protected void preProcess(ProcessingContext context) {
        super.preProcess(context);
        context.updateState("BUILDING_RESPONSE");
    }
    
    @Override
    protected void postProcess(ProcessingContext context, ProcessingResult result) {
        super.postProcess(context, result);
        if (result.isSuccess()) {
            context.updateState("RESPONSE_BUILT");
        } else {
            context.updateState("RESPONSE_BUILD_FAILED");
        }
    }
    
    @Override
    public boolean supports(ProcessingContext context) {
        // 响应处理器支持所有有基本信息的上下文
        return context != null && 
               context.getOriginalRequest() != null &&
               context.getUserId() != null &&
               context.getSessionId() != null;
    }
    
    @Override
    protected ProcessingResult handleError(ProcessingContext context, Exception exception) {
        logger.warn("Response building failed, using emergency response for requestId: {}", 
                context.getRequestId(), exception);
        
        try {
            // 创建紧急响应
            String emergencyContent = "抱歉，系统暂时出现问题，请稍后重试。如问题持续存在，请联系客服。";
            
            Map<String, Object> emergencyMetadata = new HashMap<>();
            emergencyMetadata.put("requestId", context.getRequestId());
            emergencyMetadata.put("responseTime", LocalDateTime.now());
            emergencyMetadata.put("processingSuccess", false);
            emergencyMetadata.put("emergencyResponse", true);
            emergencyMetadata.put("error", exception.getMessage());
            
            // 更新响应构建器
            context.getResponseBuilder()
                    .success(false)
                    .content(emergencyContent)
                    .errorMessage("系统异常")
                    .responseTime(LocalDateTime.now())
                    .metadata(emergencyMetadata);
            
            context.setProcessingData("responseContent", emergencyContent);
            context.setProcessingData("responseError", exception.getMessage());
            
            return ProcessingResult.builder()
                    .success(true) // 虽然出错，但成功生成了紧急响应
                    .shouldContinue(false) // 响应处理器是最后一环
                    .processorName(PROCESSOR_NAME)
                    .resultData("responseContent", emergencyContent)
                    .resultData("emergencyResponse", true)
                    .resultData("error", exception.getMessage())
                    .build();
                    
        } catch (Exception e) {
            logger.error("Failed to create emergency response for requestId: {}", 
                    context.getRequestId(), e);
            return super.handleError(context, e);
        }
    }
}